<template>
    <div class="apply">
        <navBar title="专利订单上传" @onClickLeft="onClickLeft"  />
        <van-collapse v-model="show.activeClass">
            <div class="zhanlixx">
                <van-collapse-item :title="'专利编号： '+(show.activeList.order_number||'')" name="1" v-if="show.activeList">
                    <div class="active_div" v-if="show.activeList.acceptance_note_file">
                        <van-cell :border="false" title="受理通知书" v-if="show.activeList.acceptance_note_file">
                            <template #default>
                                <a
                                    class="f20 btn_text"
                                    :href="show.activeList.acceptance_note_file"
                                    download="受理通知书"
                                >
                                    <van-icon name="notes-o" />
                                </a>
                            </template>
                        </van-cell>
                    </div>
                    <div class="active_div" v-if="show.activeList.demand_note_file">
                        <van-cell :border="false" title="缴费通知书" v-if="show.activeList.demand_note_file">
                            <template #default>
                                <a
                                    class="f20 btn_text"
                                    :href="show.activeList.demand_note_file"
                                    download="缴费通知书"
                                >
                                    <van-icon name="notes-o" />
                                </a>
                            </template>
                        </van-cell>
                    </div>
                    <div class="active_div" v-if="show.activeList.invoice_file">
                        <van-cell :border="false" title="发票" v-if="show.activeList.invoice_file">
                            <template #default>
                                <a
                                    class="f20 btn_text"
                                    :href="show.activeList.invoice_file"
                                    download="发票"
                                >
                                    <van-icon name="notes-o" />
                                </a>
                            </template>
                        </van-cell>
                    </div>
                </van-collapse-item>
            </div>
        </van-collapse>
        <div class="apply-form">
            <van-form validate-first>
                <van-field
                    class="van-field-isRequired"
                    readonly
                    clickable
                    :value="select.agency.title"
                    label="报销地点"
                    @click="showPopup(1)"
                />
                <van-field
                    class="van-field-isRequired"
                    readonly
                    clickable
                    :value="select.item.title || ''"
                    label="代办事项"
                    @click="showPopup(2)"
                />
                <van-field
                    class="van-field-isRequired"
                    readonly
                    clickable
                    :value="select.type.title || ''"
                    label="报销类型"
                    @click="showPopup(3)"
                />
                 <van-field
          class="van-field-isRequired"
          readonly
          clickable
          label="报销时间"
          :rules="[{ required: true, message: '点击选择报销时间' }]"
        >
        <template #input><div @click="showPopup(4)" v-if="post.isTimeOver != 1"><input type="text" readonly="readonly" placeholder="点击选择报销天数" class="van-field__control"  v-model="select.time.daysNum"></div><div v-else>NA</div></template>
        </van-field>
                <div>
                  <div v-if="show.activeList.isVip !== '1'">
                  <van-field
                        name="TimeOver"
                        label="发票是否过期"
                        class="needTips"
                        v-if='Object.keys(select.time).length != 0'
                    >
                    <template #input>
                        <div class="input-wrap">
                            <div class="input-header">
                        <van-radio-group v-model="post.isTimeOver" direction="horizontal" @change="switchChange">
                            <van-radio name="1">是</van-radio>
                            <van-radio name="-1">否</van-radio>
                        </van-radio-group>
                            </div>
                        <p class="tips">如果发票已经过期请勾选是，否则请勾选否</p>
                        <p class="tips">专利：2020年10月以后的发票在2021年3月31日前处理。</p>
                        </div>
                      </template>
                     </van-field>
                    
                    <van-field label="报销人员姓名" 
                      placeholder="请输入报销人员姓名" 
                      required
                      v-model="post.expenseName"
                      v-if='Object.keys(select.time).length != 0'
                       @input="expenseNameChange()"
                     />
                     </div>
                    <van-field
                      name="TimeOver"
                      label="设为自己姓名"
                      class="needTips"
                      v-if='Object.keys(select.time).length != 0 &&　show.isExpenseName'
                    >
                      <template #input>
                        <van-checkbox shape="square" v-model="post.isSetSelfName"></van-checkbox>
                      </template>
                    </van-field>
                      <van-field
                        name="payOnBehalf"
                        label="是否公务卡"
                        class="needTips"
                        v-if='Object.keys(select.time).length != 0'
                      >
                        <template #input>
                          <div class="input-wrap">
                            <div class="input-header">
                            <van-radio-group v-model="post.isOfficialCard" direction="horizontal">
                            <van-radio name="1">是公务卡</van-radio>
                            <van-radio name="-1">非公务卡</van-radio>
                            </van-radio-group>
                            </div>
                            <p style="color:#ccc">如果缴费时使用公务卡支付请勾选是公务卡，否则请勾选非公务卡</p>
                          </div>
                        </template>
                    </van-field>
                </div>
                <popup
                    ref="popup"
                    :list="show.selList"
                    @confirm="confirm"
                ></popup>
            </van-form>
            <div class="vipText" v-if="show.activeList.isVip == '1'">您是专利申请系统的VIP用户，可以免费享受免费报销功能</div>
        </div>
        <div class="apply-footer" v-show="Object.keys(select.time).length != 0" style="position: fixed;bottom:0;left:0;width:100%;height: 50px;padding: 0 16px;font-size: 14px;z-index:1;display: flex;justify-content:space-between;align-items: center;background: #fff;box-sizing: border-box;">
      <div class="footer-price">
        合计：<span style="color:#ee0a24;"><font style="font-size:12px">￥</font><font style="font-size:20px;">{{show.price.priceReal}}</font></span> <s style="color: #909399;">￥{{show.price.priceDel}}</s>
      </div>
      <div class="footer-btn">
        <van-button @click="onSubmit()" type="info" :loading="show.submitLoading" loading-text="提交中...">提交订单</van-button> 
      </div>
    </div>
    <!-- 提示 -->
    <van-dialog v-model="show.timeoverDialog" @confirm="show.timeoverDialog = false">
      <van-cell style="margin-bottom:0 !important;padding:20px 16px;"><span style="width: 100%;display: flex;justify-content: center;font-size:15px"><font color="red">{{show.msg}}</font></span></van-cell>
    </van-dialog>
    </div>
</template>
<script>
import navBar from "@cb/navBar.vue";
import popup from "@p/user/components/popup.vue";
import config from '../../../../../public/config';
import axios from "axios";
import { Dialog, Toast, Loading } from "vant";
import {get} from '../../../../../public/API/query'

export default {
    components: {
        navBar,
        popup,
    },
    data() {
        return {
            online: {
                data:{}         //接口请求的所有数据    
            },
            show: {
                activeList:{},
                timeoverDialog:false,
                submitLoading:false,
                activeClass:[],
                selList: [], //popup选择列表
                shcooesPrice: {},
                showLoad: false, //加载动画
                reallyPrice: 0, //真实价格
                price: 0, //划线价格
                defId:null, //默认id
                defData:null,//默认数据
                canUpload:false,//是否禁止上传文件
                invoice:[],//发票文件
                acceptanceNotice: [],//受通文件
                payNotice: [],//缴费通知书文件
                cover: [],  //封面文件
                catalog: [],//目录文件
                articleIndex: [], //文章首页文件
                invoiceEn: [], //发票翻译页文件
                baseUrl: process.env.VUE_APP_ORIGIN_URL,
                A_URL:process.env.VUE_APP_A_URL,
                price:{
                priceReal:'',
                priceDel:''  
                },
                msg:'',
                expand:{},
                isExpenseName:true
            },
            select: {
                agency: {},   //报销地点
                item: {},     //代办事项
                type: {},     //报销类型
                time: {},     //报销时间
                showItem:[{ title: "签字报销", id: "3" }],
            },
            post: {
                patentId:"",
                service_project:'',
                expenseCateCompanyPrice_id: "",
                isOfficialCard:null,
                patentSecret:"",
                isTimeOver:null,
                isSetSelfName:false,
                expenseName:'',
                isVip: ''
            },
            timeOverMoney:0
        };
    },
    computed: {
        originalPrice() {
            return this.show.price?`￥${this.show.price}`:"";
        },
    },
    watch: {},
    deactivated() {
        this.$destroy(true); //销毁组件
    },
    created() {
        axios.interceptors.request.use((config) => {
            this.show.showLoad = true;
            return config;
        });
        axios.interceptors.response.use((data) => {
            this.show.showLoad = false;
            return data;
        });
        this.post.patentId = this.$route.query.id
        this.post.patentSecret = this.$route.query.patentSecret
        let params = { patentId:this.post.patentId }
        this.post.patentSecret?params.patentSecret=this.post.patentSecret:""
        get('sysPatentDetail', params,(res) => {
            this.show.isExpenseName = false;
            this.show.activeList = res.data.patent
            this.post.expenseName = res.data.expenseName
            this.online = res.data.expenseCateCompanyPriceTree;
            if(res.data){
                this.online.data = res.data;
            }
            this.confirm(this.online[0],1)
            this.timeOverMoney = +res.data.timeOverMoney
             var list=localStorage.getItem('autoapply')||[];//为2021年1月1日前暂停订单计时做的标记，1月1日后面可以删除
                if(!Array.isArray(list)){
                  list=JSON.parse(list)
                }
  
                var sign=0;

                for(var i=0;i<list.length;i++){
                  if(list[i]==res.data.patent.id){
                    sign=1;break;
                  }
                }
                if(sign==0){
                  if(this.$ClosePrompt(this.$ENDTIME)){
                    Dialog.alert({
                      title: '提示',
                      message: `尊敬的用户，您好！感谢您对【我爱报销】的喜爱与信任！目前由于财务2020年度专利经费不足，专利代报只接单，所有专利订单将在2021年1月1日后继续为您代报，请悉知!`,
                    })
                  }
                  list.push(res.data.patent.id)
                  localStorage.setItem('autoapply',JSON.stringify(list))
                }
        });
    },
    methods: {
        switchChange(){
          let val;
          this.post.isTimeOver == '1'?val = this.select.type._child.filter(item => item.daysNum == 0):val = this.show.expand;
          this.post.expenseCateCompanyPrice_id = val[0].id;
          this.getReallyPrice(val[0])
        },
        getReallyPrice(val){
          this.show.price.priceReal = val.priceReal;
          this.show.price.priceDel = val.priceDel;
        },
        selectCheck(item, index) {
            if (this.post.payType == item.value) {
              this.post.payType = '0'
              this.$refs["selectItem"].forEach((item, i) => {
                item.classList.remove("clibiaos_ischcek");
              });
            }else{
              this.post.payType = item.value
              this.$refs["selectItem"].forEach((item, i) => {
                  if (i == index) {
                      item.classList.add("clibiaos_ischcek");
                  } else {
                      item.classList.remove("clibiaos_ischcek");
                  }
              });
            }
        },
        //提交订单
        onSubmit() {
          // isVIp
            if (this.post.expenseCateCompanyPrice_id) {
                this.show.submitLoading = true;
                let params = {}
                // 判断是否为vip
                if (this.show.activeList.isVip === '1') {
                  if(this.post.isOfficialCard == null ){
                    this.show.submitLoading = false;
                    let msg;
                    this.post.isOfficialCard == null ? this.show.msg = '请选择是否为公务卡':'';
                    this.show.timeoverDialog = true; 
                }else{
                this.post.patentSecret?params.patentSecret=this.post.patentSecret:""
                params.expenseCateCompanyPrice_id = this.post.expenseCateCompanyPrice_id
                params.service_project = this.post.service_project
                params.patentId = this.post.patentId;
                params.isOfficialCard = this.post.isOfficialCard == null?'':this.post.isOfficialCard
                params.invoice = this.show.activeList.invoice_file
                params.acceptanceNotice = this.show.activeList.acceptance_note_file
                params.payNotice = this.show.activeList.demand_note_file
                params.isVip = this.show.activeList.isVip
                console.log(params)
                get("sysPatentOrdersSub", params,(res) => {
                        if (res.code === 200) {
                        this.show.submitLoading = false;
                        let isNoOA = this.$store.state.user.ex_info && this.$store.state.user.ex_info.oa_phone ? false : true
                        if (isNoOA) {
                            Dialog.alert({
                            title: "提交订单成功！",
                            message:
                                "您还没有绑定OA账号，这会影响到您的订单进度，请尽快完善资料。",
                            confirmButtonText: "立即绑定",
                            closeOnClickOverlay: true
                            })
                            .then(() => {
                                this.$router.push("/user/set/setOAAccount");
                            })
                        } else {
                            Toast.success(`提交订单成功！`);
                        }
                        this.$router.push({
                            path: "/user/home",
                            query: {
                                pay_info_id: res.data.pay_info_id,
                                front_url: `${this.show.baseUrl}/user/home`,
                            },
                        });
                        } else {
                            Dialog.alert({
                                title: "提示",
                                message: res.data.split(':')[1].split(/[a-zA-Z]/.exec(res.data.split(':')[1]))[0]
                            });
                        }
                    });
                }
                }else {
                  if(this.post.expenseName == '' || this.post.isTimeOver == null || this.post.isOfficialCard == null ){
                    this.show.submitLoading = false;
                    let msg;
                    this.post.expenseName == ''?this.show.msg = '报销人员姓名不能为空':'';
                    this.post.isOfficialCard == null ? this.show.msg = '请选择是否为公务卡':'';
                    this.post.isTimeOver == null ? this.show.msg = '请选择发票是否过期':'';
                    this.show.timeoverDialog = true; 
                }else{
                this.post.patentSecret?params.patentSecret=this.post.patentSecret:""
                params.expenseCateCompanyPrice_id = this.post.expenseCateCompanyPrice_id
                params.service_project = this.post.service_project
                params.patentId = this.post.patentId;
                params.isOfficialCard = this.post.isOfficialCard == null?'':this.post.isOfficialCard
                params.isSetSelfName = this.post.isSetSelfName?'1':'-1'
                params.expenseName = this.post.expenseName
                params.isTimeOver = this.post.isTimeOver == null?'':this.post.isTimeOver;
                params.invoice = this.show.activeList.invoice_file
                params.acceptanceNotice = this.show.activeList.acceptance_note_file
                params.payNotice = this.show.activeList.demand_note_file
                params.isVip = this.show.activeList.isVip
                console.log(params)
                get("sysPatentOrdersSub", params,(res) => {
                        if (res.code === 200) {
                        this.show.submitLoading = false;
                        let isNoOA = this.$store.state.user.ex_info && this.$store.state.user.ex_info.oa_phone ? false : true
                        if (isNoOA) {
                            Dialog.alert({
                            title: "提交订单成功！",
                            message:
                                "您还没有绑定OA账号，这会影响到您的订单进度，请尽快完善资料。",
                            confirmButtonText: "立即绑定",
                            closeOnClickOverlay: true
                            })
                            .then(() => {
                                this.$router.push("/user/set/setOAAccount");
                            })
                        } else {
                            Toast.success(`提交订单成功！`);
                        }
                        this.$router.push({
                            path: "/pay/payMethod",
                            query: {
                                pay_info_id: res.data.pay_info_id,
                                front_url: `${this.show.baseUrl}/user/home`,
                            },
                        });
                        } else {
                            Dialog.alert({
                                title: "提示",
                                message: res.data.split(':')[1].split(/[a-zA-Z]/.exec(res.data.split(':')[1]))[0]
                            });
                        }
                    });
            }
                }
                
            }
        },
        deleteFile(file,detail){
          this.post[detail.name] = ""
        },
        afterRead(file, detail) {
            this.show.canUpload = true
            file.status = "uploading";
            let upfile = new FormData();
            upfile.append("file", file.file);
            var configs = {
                onUploadProgress: (progressEvent) => {
                    var schedule =
                        ((progressEvent.loaded / progressEvent.total) * 100) |
                        0;
                    file.message = schedule + "%";
                },
                timeout: 60000
            };
            axios.post(config.get('e_url')+'v1000_upload',upfile)
            .then((res) => {
                this.show.canUpload = false
                res.data.code == 200
                    ? (file.status = "success")
                    : (file.status = "failed");
                this.post[detail.name] = res.data.data;
                // this.show.reimburPath.push(res.data)
            });
        },
        //文件大小超出指定大小时执行
        onOversize() {
            Toast("文件大小不能超过 300kb");
        },
        
        //返回
        onClickLeft() {
            this.$router.go(-1);
        },
        //显示popup选择
        showPopup(i) {
            switch (i) {
                case 1:
                    // this.show.selList = this.online;
                    break;
                case 2:
                    // this.show.selList = this.select.showItem;
                    break;
                case 3:
                    // this.show.selList = this.select.agency._child;
                    break;
                case 4:
                    this.$refs["popup"].show(i);
                    if(this.select.type._child){
                      let child = this.select.type._child.filter(item => item.daysNum != 0);
                      this.show.selList = child
                    }
                    this.show.selList.map(item => {
                      if(item.daysNum != 0){
                        String(item.daysNum).indexOf('天') == -1?item.daysNum = item.daysNum+'天':item.daysNum = item.daysNum  
                      }  
                    })
                    break;
            }
        },
        //默认数据
        findDef(data){
            for (const key in data._child) {
                if (data._child[key].id == this.defId) {
                    this.defData = data._child[key]
                }
                this.findDef(data._child[key])
            }
        },
        //确定popup选择
        confirm(value, i) {
            switch (i) {
                case 1:
                    if (value) {
                      this.select.agency = value;
                      this.defId = value.company_defaultExpenseCatePriceId
                      this.findDef(value)
                      var defType;
                      for (const key in value._child) {
                          for (const key2 in value._child[key]._child) {
                              if (value._child[key]._child[key2].id == this.defId) {
                                  defType = value._child[key]
                              }
                          }
                      }
                      this.select.type = defType
                      this.select.item = this.select.showItem[0]
                      this.post.service_project = this.select.showItem[0].id
                    }
                    break;
                case 2:
                    if (value) {
                      this.select.item = value;
                      this.post.service_project = value.id
                    }
                    break;
                case 3:
                    if (value) {
                      this.select.type = value
                    }
                    break;
                case 4:
                    if (value) {
                        this.select.time = value;
                        this.post.expenseCateCompanyPrice_id = value.id;
                        this.show.shcooesPrice = value.expenseCate_fieldJson;
                        let child = this.select.type._child.filter(item => item.daysNum == value.daysNum);
                        this.getReallyPrice(child[0]);
                        this.show.expand = child;
                        this.post.isTimeOver = null;
                        // 判断是否为vip
                        if (this.show.activeList.isVip == '1') {
                          this.show.price.priceDel = 0
                          this.show.price.priceReal = 0
                        }
                    }
                    break;
            }
        },
       expenseNameChange(val){
        this.post.expenseName == this.online.data.expenseName?this.show.isExpenseName = false:this.show.isExpenseName = true
      },
    },
};
</script>
<style lang="less">
.pdf-container{
    width: 100%;
    height: 100%;
    position: absolute;
    top:0;
    left:0;
    bottom:0;
    right:0;
}
.zhanlixx{
    .van-cell__title{
        padding-left: 10px;
    }
}
.active_div{
    span{
        vertical-align: middle;
    }
    iframe{
        width: 100%;
        min-height: 300px;
        overflow-y: auto;
        border: none;
    }
}
.load_class {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.2);
    display: flex;
    position: fixed;
    left: 0;
    top: 0;
    justify-content: center;
    align-items: center;
    z-index: 3000;
}
.official_item {
    vertical-align: middle;
}
.clibiaos {
    // .outside{
    //
    // }
    float: left;
    margin-left: 15px;
    .outside {
        vertical-align: middle;
        box-sizing: content-box;
        display: inline-block;
        width: 14px;
        height: 14px;
        border-radius: 50%;
        border: 1px #006cff solid;
        margin: 0 3px 0 0;
    }
    .inside {
        box-sizing: content-box;
        display: block;
        margin: 4px 4px;
        width: 6px;
        height: 6px;
        border-radius: 50%;
    }
}
.clibiaos:first-child {
    margin-left: 0px;
}
.clibiaos_ischcek {
    .inside {
        background: #006cff;
    }
}

.up_schedule {
    background: #07c160;
    height: 10px;
    border-radius: 5px;
}
.apply {
    height: 100%;
    width: 100%;
    box-sizing: border-box;
    &-form {
        height: 100%;
        margin-top: 20px;
        // padding-bottom: 70px;]
        .van-form {
            padding-bottom: 50px;
        }
        .van-cell {
            margin-bottom: 15px;
        }
        .needTips {
            .van-field__body {
                .van-field__control {
                    align-items: flex-start;
                }
            }
            .tips {
                color: #ccc;
            }
        }
    }
    .van-submit-bar {
        // bottom: 20px;
        .van-submit-bar__bar {
            .van-submit-bar__text {
                .van-submit-bar__suffix-label {
                    text-decoration: line-through;
                    color: #909399;
                }
            }
        }
    }
}
.check-title{
  vertical-align:top;
  padding-left:8px;
}
.tips{
    color:#ccc;
}
.input-wrap{
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}
.input-header{
  display: flex;
  justify-content: flex-start;
}
.apply-footer{
  position: fixed;
  bottom:0;
  left:0;
  width:100%;
  height: 50px;
  padding: 0 16px;
  font-size: 14px;
  z-index:1;
  display: flex;
  justify-content:space-between;
  align-items: center;
  background: #fff;
  box-sizing: border-box;
}
.footer-btn>button{
  height:100%;
  width:auto;
  padding:10px 15px;
  background: rgb(0, 22, 255);
  color:#fff;
  border:none;
  border-radius:30px;
  color:#fff;
}
.apply-form {
  position: relative;;
}
.vipText {
  color: #909399;
  position: absolute;
  top: 62%;
  left: 50%;
  white-space:nowrap;
  transform: translate(-50%,-50%);
}
</style>